package jnpf.zcasset.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.util.BaseModel;
import jnpf.util.CustomException;
import jnpf.util.ZcDateUtil;
import jnpf.model.visiual.superQuery.ConditionJsonModel;
import jnpf.model.visiual.superQuery.SuperQueryConditionModel;
import jnpf.model.visiual.superQuery.SuperQueryJsonModel;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.util.*;
import jnpf.zcasset.entity.ZcAssetDisposeDetailsEntity;
import jnpf.zcasset.entity.ZcAssetDisposeEntity;
import jnpf.zcasset.entity.ZcAssetDisposeProcessEntity;
import jnpf.zcasset.entity.ZcAssetInfoEntity;
import jnpf.zcasset.mapper.ZcAssetDisposeMapper;
import jnpf.zcasset.model.zcassetdispose.ZcAssetDisposeDetailsModel;
import jnpf.zcasset.model.zcassetdispose.ZcAssetDisposeForm;
import jnpf.zcasset.model.zcassetdispose.ZcAssetDisposePagination;
import jnpf.zcasset.model.zcassetdisposeprocess.ZcAssetDisposeProcessCompleteForm;
import jnpf.zcasset.model.zcassetdisposeprocess.ZcAssetDisposeProcessForm;
import jnpf.zcasset.service.ZcAssetDisposeDetailsService;
import jnpf.zcasset.service.ZcAssetDisposeProcessService;
import jnpf.zcasset.service.ZcAssetDisposeService;
import jnpf.zcasset.service.ZcAssetInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 资产处置
 * 版本： V3.2.0
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 */
@Service
public class ZcAssetDisposeServiceImpl extends ServiceImpl<ZcAssetDisposeMapper, ZcAssetDisposeEntity> implements ZcAssetDisposeService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private ZcAssetDisposeDetailsService zcAssetDisposeDetailsService;
    @Autowired
    private ZcAssetInfoService zcAssetInfoService;
    @Autowired
    private ZcAssetDisposeProcessService zcAssetDisposeProcessService;

    @Override
    public List<ZcAssetDisposeEntity> getList(ZcAssetDisposePagination zcAssetDisposePagination) {
        return getTypeList(zcAssetDisposePagination, zcAssetDisposePagination.getDataType());
    }

    @Override
    public List<ZcAssetDisposeEntity> getTypeList(ZcAssetDisposePagination zcAssetDisposePagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int zcAssetDisposeNum = 0;
        QueryWrapper<ZcAssetDisposeEntity> zcAssetDisposeQueryWrapper = new QueryWrapper<>();
        int zcAssetDisposeDetailsNum = 0;
        QueryWrapper<ZcAssetDisposeDetailsEntity> zcAssetDisposeDetailsQueryWrapper = new QueryWrapper<>();
        long zcAssetDisposeDetailscount = zcAssetDisposeDetailsService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(zcAssetDisposePagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcAssetDisposePagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            int zcAssetDisposeNum1 = 0;
            QueryWrapper<ZcAssetDisposeEntity> zcAssetDisposeSuperWrapper = new QueryWrapper<>();
            zcAssetDisposeNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcAssetDisposeSuperWrapper, superQueryList, matchLogic, "zcAssetDispose")
                    , new ZcAssetDisposeEntity(), zcAssetDisposeNum1);
            if (zcAssetDisposeNum1 > 0) {
                List<String> zcAssetDisposeList = this.list(zcAssetDisposeSuperWrapper).stream().map(ZcAssetDisposeEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(zcAssetDisposeList);
                intersectionSuperList.add(zcAssetDisposeList);
            }
            int zcAssetDisposeDetailsNum1 = 0;
            QueryWrapper<ZcAssetDisposeDetailsEntity> zcAssetDisposeDetailsSuperWrapper = new QueryWrapper<>();
            zcAssetDisposeDetailsNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcAssetDisposeDetailsSuperWrapper, superQueryList, matchLogic, "zcAssetDisposeDetails")
                    , new ZcAssetDisposeDetailsEntity(), zcAssetDisposeDetailsNum1);
            if (zcAssetDisposeDetailsNum1 > 0 && zcAssetDisposeDetailscount > 0) {
                List<String> zcAssetDisposeDetailsList = zcAssetDisposeDetailsService.list(zcAssetDisposeDetailsSuperWrapper).stream().map(ZcAssetDisposeDetailsEntity::getAssetDisposeId).collect(Collectors.toList());
                allSuperList.addAll(zcAssetDisposeDetailsList);
                intersectionSuperList.add(zcAssetDisposeDetailsList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcAssetDisposeObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetDisposeQueryWrapper, zcAssetDisposePagination.getMenuId(), "zc_asset_dispose"));
                if (ObjectUtil.isEmpty(zcAssetDisposeObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetDisposeQueryWrapper = (QueryWrapper<ZcAssetDisposeEntity>) zcAssetDisposeObj;
                    zcAssetDisposeNum++;
                }
                Object zcAssetDisposeDetailsObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetDisposeDetailsQueryWrapper, zcAssetDisposePagination.getMenuId(), "zc_asset_dispose_details"));
                if (ObjectUtil.isEmpty(zcAssetDisposeDetailsObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetDisposeDetailsQueryWrapper = (QueryWrapper<ZcAssetDisposeDetailsEntity>) zcAssetDisposeDetailsObj;
                    zcAssetDisposeDetailsNum++;
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcAssetDisposeObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetDisposeQueryWrapper, zcAssetDisposePagination.getMenuId(), "zcAssetDispose"));
                if (ObjectUtil.isEmpty(zcAssetDisposeObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetDisposeQueryWrapper = (QueryWrapper<ZcAssetDisposeEntity>) zcAssetDisposeObj;
                    zcAssetDisposeNum++;
                }
                Object zcAssetDisposeDetailsObj = authorizeService.getCondition(new AuthorizeConditionModel(zcAssetDisposeDetailsQueryWrapper, zcAssetDisposePagination.getMenuId(), "zcAssetDisposeDetails"));
                if (ObjectUtil.isEmpty(zcAssetDisposeDetailsObj)) {
                    return new ArrayList<>();
                } else {
                    zcAssetDisposeDetailsQueryWrapper = (QueryWrapper<ZcAssetDisposeDetailsEntity>) zcAssetDisposeDetailsObj;
                    zcAssetDisposeDetailsNum++;
                }
            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(zcAssetDisposePagination.getDisposalTitle())) {
                zcAssetDisposeNum++;
                zcAssetDisposeQueryWrapper.lambda().like(ZcAssetDisposeEntity::getDisposalTitle, zcAssetDisposePagination.getDisposalTitle());
            }

            if (ObjectUtil.isNotEmpty(zcAssetDisposePagination.getDisposalType())) {
                zcAssetDisposeNum++;
                zcAssetDisposeQueryWrapper.lambda().eq(ZcAssetDisposeEntity::getDisposalType, zcAssetDisposePagination.getDisposalType());
            }

            if (ObjectUtil.isNotEmpty(zcAssetDisposePagination.getStartDate())) {
                zcAssetDisposeNum++;
                List StartDateList = JsonUtil.getJsonToList(zcAssetDisposePagination.getStartDate(), String.class);
                Long fir = Long.valueOf(String.valueOf(StartDateList.get(0)));
                Long sec = Long.valueOf(String.valueOf(StartDateList.get(1)));

                zcAssetDisposeQueryWrapper.lambda().ge(ZcAssetDisposeEntity::getStartDate, new Date(fir))
                        .le(ZcAssetDisposeEntity::getStartDate, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));

            }

            if (ObjectUtil.isNotEmpty(zcAssetDisposePagination.getDisposalAgent())) {
                zcAssetDisposeNum++;
                zcAssetDisposeQueryWrapper.lambda().like(ZcAssetDisposeEntity::getDisposalAgent, zcAssetDisposePagination.getDisposalAgent());
            }

            if (ObjectUtil.isNotEmpty(zcAssetDisposePagination.getDisposalUnit())) {
                zcAssetDisposeNum++;
                zcAssetDisposeQueryWrapper.lambda().eq(ZcAssetDisposeEntity::getDisposalUnit, zcAssetDisposePagination.getDisposalUnit());
            }

            if (ObjectUtil.isNotEmpty(zcAssetDisposePagination.getDisposalSpecification())) {
                zcAssetDisposeNum++;
                zcAssetDisposeQueryWrapper.lambda().like(ZcAssetDisposeEntity::getDisposalSpecification, zcAssetDisposePagination.getDisposalSpecification());
            }

        }
        if (zcAssetDisposeDetailsNum > 0) {
            List<String> zcAssetDisposeDetailsIdList = zcAssetDisposeDetailsService.list(zcAssetDisposeDetailsQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getAssetDisposeId())).map(t -> t.getAssetDisposeId()).collect(Collectors.toList());
            long count = zcAssetDisposeDetailsService.count();
            if (count > 0) {
                intersectionList.add(zcAssetDisposeDetailsIdList);
            }
            AllIdList.addAll(zcAssetDisposeDetailsIdList);
        }
        total += zcAssetDisposeDetailsNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            zcAssetDisposeQueryWrapper.lambda().in(ZcAssetDisposeEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            zcAssetDisposeQueryWrapper.lambda().and(t -> t.in(ZcAssetDisposeEntity::getId, finalAllSuperIDlist));
        }

        //排序
        if (StringUtil.isEmpty(zcAssetDisposePagination.getSidx())) {
            zcAssetDisposeQueryWrapper.lambda().orderByDesc(ZcAssetDisposeEntity::getId);
        } else {
            try {
                String sidx = zcAssetDisposePagination.getSidx();
                ZcAssetDisposeEntity zcAssetDisposeEntity = new ZcAssetDisposeEntity();
                Field declaredField = zcAssetDisposeEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                zcAssetDisposeQueryWrapper = "asc".equals(zcAssetDisposePagination.getSort().toLowerCase()) ? zcAssetDisposeQueryWrapper.orderByAsc(value) : zcAssetDisposeQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<ZcAssetDisposeEntity> page = new Page<>(zcAssetDisposePagination.getCurrentPage(), zcAssetDisposePagination.getPageSize());
                IPage<ZcAssetDisposeEntity> userIPage = this.page(page, zcAssetDisposeQueryWrapper);
                return zcAssetDisposePagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<ZcAssetDisposeEntity> list = new ArrayList();
                return zcAssetDisposePagination.setData(list, list.size());
            }
        } else {
            return this.list(zcAssetDisposeQueryWrapper);
        }
    }

    @Override
    public ZcAssetDisposeEntity getInfo(String id) {
        QueryWrapper<ZcAssetDisposeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcAssetDisposeEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcAssetDisposeEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcAssetDisposeEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(ZcAssetDisposeEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    //子表方法
    @Override
    public List<ZcAssetDisposeDetailsEntity> getZcAssetDisposeDetailsList(String id, ZcAssetDisposePagination zcAssetDisposePagination) {
        QueryWrapper<ZcAssetDisposeDetailsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = zcAssetDisposeDetailsService.getChild(zcAssetDisposePagination, queryWrapper);
        queryWrapper.lambda().eq(ZcAssetDisposeDetailsEntity::getAssetDisposeId, id);
        return zcAssetDisposeDetailsService.list(queryWrapper);
    }

    @Override
    public List<ZcAssetDisposeDetailsEntity> getZcAssetDisposeDetailsList(String id) {
        QueryWrapper<ZcAssetDisposeDetailsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcAssetDisposeDetailsEntity::getAssetDisposeId, id);
        return zcAssetDisposeDetailsService.list(queryWrapper);
    }

    //列表子表数据方法    //验证表单唯一字段
    @Override
    public boolean checkForm(ZcAssetDisposeForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        if (isUp) {
            id = form.getId();
        }
        if (form.getZcassetdisposedetailsList() != null) {
        }
        if (total > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<ZcAssetDisposeDetailsModel> getZcAssetDisposeDetailsModelList(String assetDisposeId) {
        return baseMapper.queryZcAssetDisposeDetailsModelList(assetDisposeId);
    }

    @Override
    public List<ZcAssetInfoEntity> queryAssetListById(String assetDisposeId) {
        LambdaQueryWrapper<ZcAssetDisposeDetailsEntity> detailsWrapper = new LambdaQueryWrapper<>();
        detailsWrapper.select(ZcAssetDisposeDetailsEntity::getAssetId);
        detailsWrapper.eq(ZcAssetDisposeDetailsEntity::getAssetDisposeId, assetDisposeId);
        List<String> assetIdList = zcAssetDisposeDetailsService.listObjs(detailsWrapper, o -> o.toString());
        if (StringUtil.isNotEmpty(assetIdList))
            return zcAssetInfoService.lambdaQuery().in(BaseModel::getId, assetIdList).list();
        else
            return new ArrayList<>();
    }

    @Override
    public List<ZcAssetDisposeProcessEntity> queryDisposeProcessList(String assetDisposeId) {
        return zcAssetDisposeProcessService.lambdaQuery().eq(ZcAssetDisposeProcessEntity::getAssetDisposeId, assetDisposeId)
                .eq(ZcAssetDisposeProcessEntity::getType, 2).orderByDesc(BaseModel::getCreatorTime).list();
    }

    @Override
    public boolean addDisposeProcess(ZcAssetDisposeProcessForm form) {
        ZcAssetDisposeProcessEntity entity = JsonUtil.getJsonToBean(form, ZcAssetDisposeProcessEntity.class);
        return zcAssetDisposeProcessService.save(entity);
    }

    @Override
    @Transactional
    public boolean addDisposeProcessComplete(ZcAssetDisposeProcessCompleteForm form) {
        ZcAssetDisposeEntity dispose = baseMapper.selectById(form.getAssetDisposeId());
        if (dispose == null)
            throw new CustomException("处置信息不存在");

        ZcAssetDisposeProcessEntity entity = JsonUtil.getJsonToBean(form, ZcAssetDisposeProcessEntity.class);
        boolean bool = zcAssetDisposeProcessService.save(entity);
        if (bool) {
//            dispose.setDisposalCompletionTime(DateUtil.stringToDate(form.getCompleteDate()));
            bool = lambdaUpdate().set(ZcAssetDisposeEntity::getDisposalCompletionTime, ZcDateUtil.stringTimestampToDate(form.getCompleteDate())).eq(BaseModel::getId, form.getAssetDisposeId()).update();
            if (!bool) {
//            if (!SqlHelper.retBool(baseMapper.updateById(dispose))) {
                throw new CustomException("更新处置信息失败");
            }
        }
        return bool;
    }
}
